from datetime import datetime, timedelta, date
import json
from urllib3 import Retry, PoolManager
from pathlib import Path
import os
import threading
import logging
retries = Retry(connect=5, read=5, redirect=5, backoff_factor=1)

user_mapping = {
    "planter": '14726',
    "longkk": '13146',
    "forke009": '15283',
    "guangyun1": '15185',
    "guangguang": '15189',
    "alinger001": '16519',
    "shrewdtony": '15195'
    # "alinger123": '16522',
    # "yunyun": '15188',
    # "alinger666": '16523',
    # "alinger163": '16525'
}


def get_user_status(userid: str):
    now = datetime.utcnow()
    today = date.today()
    start = today - timedelta(days=today.weekday())
    now_str = now.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
    firstday_str = start.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
    url = f'https://api.ironfish.network/users/{userid}/metrics?granularity=total&start={firstday_str}&end={now_str}'
    http = PoolManager(retries=retries)
    response = http.request('GET', url)
    cont = json.loads(response.data.decode('utf-8'))
    print(userid)
    print(cont)
    _metrics = cont['metrics']['blocks_mined']['count']
    if _metrics >= 10:
        return True
    return False


def json_load() -> str:
    f = open(f'{str(Path.home())}/.ironfish/config.json')
    data = json.load(f)
    current_user = data['blockGraffiti']
    f.close()
    return current_user


def run():
    for k, v in user_mapping.items():
        if get_user_status(v) == False:
            # 设定当前执行的是这个任务
            print(k)
            # 当前正在挖
            if json_load() != k:
                command=f"""
                sudo docker run --rm -i --network host --volume $HOME/.ironfish:/root/.ironfish ghcr.io/iron-fish/ironfish:latest config:set blockGraffiti "{k}";
                """.replace('\n',' ')
                process = os.popen(command)
                print(process.read())
                # process = os.popen('docker stop $(docker ps -a -q)')
                # docker run --rm -it --network host --volume $HOME/.ironfish:/root/.ironfish ghcr.io/iron-fish/ironfish:latest config:set blockGraffiti "planter"
                # process = os.popen(f'docker run --rm -it --network host --volume $HOME/.ironfish:/root/.ironfish ghcr.io/iron-fish/ironfish:latest config:set blockGraffiti "{k}"')
                # process = os.popen('docker start $(docker ps -a -q)')
                break


def set_interval(func, sec):
    def func_wrapper():
        set_interval(func, sec)
        func()
    t = threading.Timer(sec, func_wrapper)
    t.start()
    return t
run()
set_interval(run,60*20)